// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

package handler

import (
	"encoding/json"
	"net/http"

	"slices"

	"github.com/gorilla/mux"
	"github.com/kumose/fn"
	logprinter "github.com/kumose/kmopt/pkg/logger/printer"
	"github.com/kumose/kmopt/pkg/repository"
	"github.com/kumose/kmopt/pkg/repository/model"
	"github.com/kumose/kmopt/pkg/repository/v1manifest"
	"github.com/kumose/kmopt/server/session"
)

// SignComponent handles requests to re-sign component manifest
func SignComponent(sm session.Manager, mirror repository.Mirror) http.Handler {
	return &componentSigner{sm, mirror}
}

type componentSigner struct {
	sm     session.Manager
	mirror repository.Mirror
}

func (h *componentSigner) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	fn.Wrap(h.sign).ServeHTTP(w, r)
}

func buildInfo(r *http.Request, sid string) *model.PublishInfo {
	info := &model.PublishInfo{}

	m := map[string]**bool{
		repository.OptionYanked:     &info.Yank,
		repository.OptionStandalone: &info.Stand,
		repository.OptionHidden:     &info.Hide,
	}

	for k, v := range m {
		f := false
		if query(r, k) == "true" {
			f = true
			*v = &f
		} else if query(r, k) == "false" {
			*v = &f
		}
	}

	return info
}

func (h *componentSigner) sign(r *http.Request, m *v1manifest.RawManifest) (sr *simpleResponse, err statusError) {
	sid := mux.Vars(r)["sid"]
	name := mux.Vars(r)["name"]
	info := buildInfo(r, sid)

	blackList := []string{"root", "index", "snapshot", "timestamp"}
	if slices.Contains(blackList, name) {
		return nil, ErrorForbiden
	}

	logprinter.Infof("Sign component manifest for %s, sid: %s", name, sid)
	fileName, readCloser, rErr := h.sm.Read(sid)
	if rErr != nil {
		logprinter.Errorf("Read tar info for component %s, sid: %s", name, sid)
		return nil, ErrorInternalError
	}
	info.ComponentData = &model.TarInfo{
		Reader: readCloser,
		Name:   fileName,
	}

	comp := v1manifest.Component{}
	if err := json.Unmarshal(m.Signed, &comp); err != nil {
		logprinter.Errorf("Unmarshal manifest %s", err.Error())
		return nil, ErrorInvalidManifest
	}

	manifest := &v1manifest.Manifest{
		Signatures: m.Signatures,
		Signed:     &comp,
	}

	switch err := h.mirror.Publish(manifest, info); err {
	case model.ErrorConflict:
		return nil, ErrorManifestConflict
	case model.ErrorWrongSignature:
		return nil, ErrorForbiden
	case model.ErrorWrongChecksum, model.ErrorWrongFileName:
		logprinter.Errorf("Publish component: %s", err.Error())
		return nil, ErrorInvalidTarball
	case nil:
		return nil, nil
	default:
		h.sm.Delete(sid)
		logprinter.Errorf("Publish component: %s", err.Error())
		return nil, ErrorInternalError
	}
}

func query(r *http.Request, q string) string {
	qs := r.URL.Query()[q]

	if len(qs) == 0 {
		return ""
	}

	return qs[0]
}
